//基本流程中事件配置
//事件表格
var event_main_grid;

/**
 * 创建基础Form grid Event
 */
function createEventMainGrid(flag){
    event_main_grid=
        "<div class=\"m-portlet\" style='height:150px;overflow: auto;'>"+
			"<div class=\"m-portlet__head\">"+
				"<div class=\"m-portlet__head-caption\">" +
					"<button type=\"button\" class=\"btn btn-light-primary mr-3 m-btn--custom m-btn--icon\" onclick=\"newMainListenerRows("+flag+")\" title='选择监听器'><i class=\"la la-plus\"></i>选择监听器</button>"+
					// "&nbsp;&nbsp;<input type=\"button\" class=\"btn btn-success m-btn m-btn--custom m-btn--icon\" value='保存' onclick='event_main_setvalue()'>"+
				"</div>"+
			"</div>"+

			"<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" id=\"node_main_event\" method=\"post\">"+
				"<div class=\"m-portlet__body\" id='node_event_main_grid'>"+
					//Title
					"<div class=\"form-group m-form__group row\" style='background: #f2f3f5;'>"+
                        "<div class=\"col-md-2\">名称</div>"+
						"<div class=\"col-md-2\">值</div>"+
						"<div class=\"col-md-1\">类型</div>"+
						"<div class=\"col-md-1\">事件</div>"+
						"<div class=\"col-md-6\">字段</div>"+
                        "<div class=\"col-md-2\">分类</div>"+
						"<div class=\"col-md-1\"></div>"+
					"</div>"+
				"</div>"+
			"</form>"+
        "</div>";
    return event_main_grid;
}

/**
 * 新一行
 * @param flag
 */
function newMainListenerRows(flag) {
    initMainListener(flag);
}
/**
 * 新一行
 * @param flag
 * @param javaclass_express
 * @param event_type
 * @param event
 * @param fields
 */
function addEventMainRow(flag,javaclass_express,event_type,event,fields,lc_listener_id,lc_listener_name,categories){
    if(javaclass_express === undefined){
        javaclass_express = "";
    }
    if(event_type === undefined){
        event_type = "";
    }
    if(event === undefined){
        event = "";
    }
    if(fields === undefined){
        fields = "";
    }
    if(lc_listener_id === undefined){
        lc_listener_id = "";
    }
    if(lc_listener_name === undefined){
        lc_listener_name = "";
    }
    if(categories === undefined){
        categories = "";
    }
    var uuid = guid();
    validatorDestroy('node_main_event');
    var event_typeOption;
    var event_option;
    if(flag == 1){
        event_option =  "<option value=''>请选择</option>" +
            "<option value='start'>start</option>" +
            "<option value='end'>end</option>";
    }else if(flag == 3){
        event_option =  "<option value=''>请选择</option>" +"<option value='take'>take</option>";
    }else{
        event_option = "<option value=''>请选择</option>" +
            "<option value='create'>create</option>" +
            "<option value='assignment'>assignment</option>"+
            "<option value='complete'>complete</option>"+
            "<option value='all'>all</option>";
    }
    var event_typeOption = "<option value=''>请选择</option>" +
        "<option value='javaclass'>Java类</option>" +
        "<option value='express'>表达式</option>"+
        "<option value='delegateExpression'>委托表达式</option>"+
        "<option value='ScriptExecutionListener'>脚本执行监听器</option>"+
        "<option value='ScriptTaskListener'>脚本任务监听器</option>";

    var rows =
        "<div class=\"form-group m-form__group row\" id='node_event_main_rows_"+uuid+"'>"+
            //名称
            "<div class=\"col-md-2\">"+
                "<input class=\"form-control\" type=\"hidden\" readonly id='lc_listener_id"+uuid+"' name='nodeEventMain[][lc_listener_id]' value='"+lc_listener_id+"'>"+
                "<input class=\"form-control\" type=\"text\" readonly id='lc_listener_name"+uuid+"' name='nodeEventMain[][lc_listener_name]' value='"+lc_listener_name+"'>"+
            "</div>"+

			//执行的类或表达式
			"<div class=\"col-md-2\">"+
				"<input class=\"form-control\" type=\"text\"  data-bv-notempty data-bv-notempty-message='请输入' id='javaclass_express"+uuid+"' name='nodeEventMain[][javaclass_express]' value='"+javaclass_express+"' placeholder='请输入'>"+
			"</div>"+

			//类型
			"<div class=\"col-md-1\">"+
				"<select class=\"form-control\" id='event_type"+uuid+"' name=\"nodeEventMain[][event_type]\">" +
				event_typeOption+
				"</select>"+
			"</div>"+

			//事件
			"<div class=\"col-md-1\">"+
				"<select class=\"form-control\" id='event"+uuid+"' name=\"nodeEventMain[][event]\">" +
				event_option+
				"</select>"+
			"</div>"+

			//配置字段
			"<div class=\"col-md-6\">"+
				"<input class=\"form-control\" type=\"text\" readonly='readonly' onclick='showFieldMainWin(this,\""+uuid+"\")' id='fields"+uuid+"' name=\"nodeEventMain[][fields]\" value='"+fields+"' placeholder=\"请选择字段\">"+
			"</div>"+

            "<div class=\"col-md-1\">"+
                "<input class=\"form-control\" type=\"text\"id='categories"+uuid+"' name=\"nodeEventMain[][categories]\" value='"+categories+"' placeholder=\"暂无\">"+
            "</div>"+
			//操作
			"<div class=\"col-md-1\">"+
				"<button type=\"button\" class=\"btn m-btn--square  btn-secondary\" onclick='delEventMainRow(\""+uuid+"\")'>删除</button>"+
			"</div>"+
        "</div>";
    $("#node_event_main_grid").append(rows);
    $("#event_type"+uuid).val(event_type);
    $("#event"+uuid).val(event);
    reValidator('node_main_event');
}

/**
 * 删除
 * @param rowID
 */
function delEventMainRow(rowID){
    msgTishCallFnBoot("确认删除？",function(){
        validatorDestroy('node_main_event');
        $("#node_event_main_rows_"+rowID).remove();
        reValidator('node_main_event');
    });
}

/**
 * 初始化init event grid
 * @param cell
 * @param flag
 */
function initeventmain_grid(flag){
    //表单配置
    $('#node_main_event').bootstrapValidator({
        message:'此值不是有效的'
    });
    initeventmain_data(flag);
}


/**
 *
 * @param cell
 * @param flag
 */
function initeventmain_data(flag){
    var event_node_value = $("#eventMainNode").val();
    if(null != event_node_value && "" != event_node_value){
        event_node_value = eval('(' + event_node_value + ')');
        event_node_value = event_node_value.nodeEventMain;
        if(event_node_value != undefined){
            for(var i = 0; i < event_node_value.length; i++){
                var javaclass_express = event_node_value[i].javaclass_express;
                var event_type = event_node_value[i].event_type;
                var event = event_node_value[i].event;
                var fields = event_node_value[i].fields;
                addEventMainRow(flag,javaclass_express,event_type,event,fields);
            }
        }

    }
}


/**
 * 配置事件字段
 * @param thiz
 * @param id
 */
var fieldMainGrid;
function showFieldMainWin(thiz,id){
    $('#jehcLcModalLabel').empty();
    $('#jehcLcForm').empty();
    $('#jehcLcModalLabel').append("配置事件字段属性");
    fieldMainGrid = creatFieldMainGrid(id);
    $("#jehcLcForm").append(fieldMainGrid);
    $('#eventMainField').bootstrapValidator({
        message:'此值不是有效的'
    });
    initEventMainField(id);//初始化数据
    $('#jehcLcModal').modal({backdrop: 'static', keyboard: false});
}


/**
 * 创建事件字段
 * @param cell
 */
function creatFieldMainGrid(id){
    fieldMainGrid=
        "<div class=\"m-portlet\" style='height:350px;overflow: auto;'>"+
			"<div class=\"m-portlet__head\">"+
				"<div class=\"m-portlet__head-caption\">" +
					"<button type=\"button\" class=\"btn btn-info m-btn m-btn--custom m-btn--icon\" onclick=\"addEventMainFieldRow()\">新一行</button>"+
					"&nbsp;&nbsp;<button type=\"button\" class=\"btn btn-success m-btn m-btn--custom m-btn--icon\" onclick='saveEventMainField(\""+id+"\")'>保存</button>"+
					"&nbsp;&nbsp;<button type=\"button\" class=\"btn btn-secondary m-btn m-btn--custom m-btn--label-danger m-btn--bolder m-btn--uppercase\" onclick=\"closeJehcLcWin()\">关闭</button>"+
				"</div>"+
			"</div>"+

		"<form class=\"m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed\" id=\"eventMainField\" method=\"post\">"+
			"<div class=\"m-portlet__body\" id='event_main_fields_grid'>"+
				//Title
				"<div class=\"form-group m-form__group row\" style='background: #f2f3f5;'>"+
					"<div class=\"col-md-3\">字段名称</div>"+
					"<div class=\"col-md-2\">字段类型</div>"+
					"<div class=\"col-md-4\">字段值</div>"+
					"<div class=\"col-md-1\">操作</div>"+
				"</div>"+
			"</div>"+
        "</form>"+
        "</div>";
    return fieldMainGrid;
}


/**
 * 初始化事件字段数据
 * @param id
 */
function initEventMainField(id){
    var fields = $("#fields"+id).val();
    if(null != fields && "" != fields){
        fields = eval('(' + fields + ')');
        fields=fields.fieldList;
        for(var i = 0; i < fields.length; i++){
            var fieldName = fields[i].fieldName;
            var fieldtype = fields[i].fieldtype;
            var fieldValue = fields[i].fieldValue;
            addEventMainFieldRow(fieldName,fieldtype,fieldValue);
        }
    }
}


/**
 * 动态添加 新一行 ”事件字段“
 * @param fieldName
 * @param fieldtype
 * @param fieldValue
 */
function addEventMainFieldRow(fieldName,fieldtype,fieldValue){
    validatorDestroy('eventMainField');
    var uuid = guid();
    if(fieldName === undefined){
        fieldName = "";
    }
    if(fieldtype === undefined){
        fieldtype = "";
    }
    if(fieldValue === undefined){
        fieldValue = "";
    }
    var fieldtypeOption =
        "<option value=''>请选择</option>" +
        "<option value='string'>string</option>"+
        "<option value='expression'>expression</option>";
    var rows =
        "<div class=\"form-group m-form__group row\" id='event_main_fields_rows_"+uuid+"'>"+
			//名称
			"<div class=\"col-md-3\">"+
				"<input class=\"form-control\" type=\"text\"  data-bv-notempty data-bv-notempty-message='请输入字段名称' id='fieldName"+uuid+"' value='"+fieldName+"' name='fieldList[][fieldName]' placeholder='请输入字段名称'>"+
			"</div>"+

			//类型
			"<div class=\"col-md-2\">"+
				"<select class=\"form-control\" id='fieldtype"+uuid+"' name=\"fieldList[][fieldtype]\">" +
					fieldtypeOption+
				"</select>"+
			"</div>"+

			//值
			"<div class=\"col-md-4\">"+
				"<input class=\"form-control\" type=\"text\"  data-bv-notempty data-bv-notempty-message=\"请输入值\" id='fieldValue"+uuid+"' value='"+fieldValue+"' name='fieldList[][fieldValue]' placeholder='请输入值'>"+
			"</div>"+

			//操作
			"<div class=\"col-md-1\">"+
				"<button type=\"button\" class=\"btn m-btn--square  btn-secondary\" onclick='delEventMainFieldRow(\""+uuid+"\")'>删除</button>"+
			"</div>"+
        "</div>";
    $("#event_main_fields_grid").append(rows);
    $("#fieldtype"+uuid).val(fieldtype);
    reValidator('eventMainField');
}


/**
 * 保存配置字段
 * @param id
 */
function saveEventMainField(id){
    var bootform = $('#eventMainField');
    var boostrapValidator =bootform.data('bootstrapValidator');
    boostrapValidator.validate();
    if(!boostrapValidator.isValid()){
        window.parent.toastrBoot(4,"存在不合法的字段!");
        return;
    }
    $("#fields"+id).val(JSON.stringify($("#eventMainField").serializeJSON()));
    closeJehcLcWin();
}

/**
 * 删除事件字段
 * @param id
 */
function delEventMainFieldRow(id){
    validatorDestroy('eventMainField');
    $("#event_main_fields_rows_"+id).remove();
    reValidator('eventMainField');
}


/**
 * 点击确定按钮设置mxgraph中cell属性
 * @param cell
 * @returns {boolean}
 */
function event_main_setvalue(cell){
    var bootform = $('#node_main_event');
    var boostrapValidator =bootform.data('bootstrapValidator');
    boostrapValidator.validate();
    if(!boostrapValidator.isValid()){
        window.parent.toastrBoot(4,"存在不合法的字段!");
        return false;
    }
    var event_node_value = JSON.stringify($("#node_main_event").serializeJSON());
    if(null != event_node_value && "" != event_node_value){
        $("#eventMainNode").val(event_node_value);
    }else{
        $("#eventMainNode").val("");
    }
    return true;
}





/**
 * 选择流程监听器
 */
function initMainListener(categories) {
    if(undefined === categories){
        toastrBoot(3,"未指定分类");
        return;
    }
    if(categories == 0){
        $("#categories").val("200");//执行监听
    }
    var listenerSelectModalCount = 0 ;
    $('#listenerSelectModal').modal({backdrop: 'static', keyboard: false});
    $('#listenerSelectModal').on("shown.bs.modal",function(){
        if(++listenerSelectModalCount == 1){
            $('#searchFormlistener')[0].reset();
            var opt = {
                searchformId:'searchFormlistener'
            };
            var options = DataTablesPaging.pagingOptions({
                ajax:function (data, callback, settings){datatablesCallBack(data, callback, settings,workflowModules+'/lcListener/list',opt);},//渲染数据
                //在第一位置追加序列号
                fnRowCallback:function(nRow, aData, iDisplayIndex){
                    jQuery('td:eq(0)', nRow).html(iDisplayIndex+1);
                    return nRow;
                },
                order:[],//取消默认排序查询,否则复选框一列会出现小箭头
                tableHeight:'120px',
                //列表表头字段
                colums:[
                    {
                        data:'lc_listener_id'
                    },
                    {
                        data:'categories',
                        render:function(data, type, row, meta) {
                            if(data == 100){
                                return "任务监听"
                            }

                            if(data == 200){
                                return "执行监听"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'lc_listener_name'
                    },
                    {
                        data:'type',
                        render:function(data, type, row, meta) {
                            if(data == 'javaclass'){
                                return "Java类"
                            }

                            if(data == 'express'){
                                return "表达式"
                            }

                            if(data == 'delegateExpression'){
                                return "委托表达式"
                            }

                            if(data == 'ScriptExecutionListener'){
                                return "脚本执行监听器"
                            }

                            if(data == 'ScriptTaskListener'){
                                return "脚本任务监听器"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'event'
                    },
                    {
                        data:'del_flag',
                        render:function(data, type, row, meta) {
                            if(data == 0){
                                return "<font style='color:#0a6aa1 '>生效</font>"
                            }

                            if(data == 1){
                                return "禁用"
                            }
                            return "缺省"
                        }
                    },
                    {
                        data:'productName'
                    },
                    {
                        data:'groupName'
                    },
                    {
                        data:"lc_listener_id",
                        render:function(data, type, row, meta) {
                            var lc_listener_id = row.lc_listener_id;
                            var btn = '<button class="btn btn-secondary m-btn m-btn--custom" onclick=doSelectMainListener("'+lc_listener_id+'","'+categories+'")><span><span>确 认</span></span></button>';
                            return btn;
                        }
                    }
                ]
            });
            grid=$('#listenerDatatables').dataTable(options);
            //实现单击行选中
            clickrowselected('listenerDatatables');
        }
    });
}

/**
 * 选择监听器配置项
 * @param data
 */
function doSelectMainListener(lc_listener_id,flag) {
    console.log(lc_listener_id,flag);
    msgTishCallFnBoot("确定选择该配置项？",function(){
        $.ajax({
            type:"GET",
            url:workflowModules+"/lcListener/get/"+lc_listener_id,
            success: function(result){
                if(complateAuth(result)){
                    try {
                        result = result.data;
                        console.log(result);
                        var lc_listener_id = result.lc_listener_id;
                        var lc_listener_name = result.lc_listener_name;
                        var categories  =  result.categories;//分类：100任务监听 200执行监听 300基于连线执行监听
                        var event = result.event;//事件类型：create，assignment，complete，all | start，end | start，end，take
                        var listener_val = result.listener_val;//事件值
                        var type = result.type;//监听类型：javaclass，express，delegateExpression，ScriptExecutionListener，ScriptTaskListener
                        var javaclass_express = listener_val;//充当表达式或类路径或委托表达式
                        var event_type = type; //充当类型
                        if(categories == 100){
                            categories = "任务监听";
                        }
                        if(categories == 200){
                            categories = "执行监听";
                        }
                        if(categories == 300){
                            categories = "基于连线执行监听";
                        }
                        addEventMainRow(flag,javaclass_express,event_type,event,"",lc_listener_id,lc_listener_name,categories);
                        event_main_setvalue();
                    } catch (e) {
                        console.log("查询监听器异常："+e);
                    }
                }
                $('#listenerSelectModal').modal('hide');
            }
        });
    });
}